<?php
/**
 * Created by PhpStorm.
 * User: xiaomage
 * Date: 2020/12/8
 * Time: 13:28
 */

namespace app\system\controller;

use app\BaseController;
use common\ApiReturn;
use component\system\system_message\SystemMessage;
use component\system\system_message\SystemMessageValidate;
use think\exception\ValidateException;

class System extends BaseController
{
    /**
     * 验证是否授权
     * @var array
     */
    protected $middleware = [
        'Authorize',
        'ApiAuth',
        'ApiAction'
    ];

    public function initialize()
    {
        parent::initialize();
    }

    /**
     * 给用户发送站内消息
     * @return \think\Response
     */
    public function sendUserMessage()
    {
        $user_id = request()->param('user_id');
        $data = request()->only(['title', 'message']);

        if (empty($user_id)) {
            return ApiReturn::error('请选择一个用户');
        }

        try {
            $this->validate($data, SystemMessageValidate::class);
        } catch (ValidateException $exception) {
            return ApiReturn::validate($exception->getMessage());
        }

        $lists = [];

        foreach ($user_id as $item) {
            $item = json_decode($item, true);
            if (isset($item[1])) {
                $data['user_id'] = $item[1];
                $lists[] = $data;
            }
        }

        $result = SystemMessage::instance()->saveAll($lists);

        return ApiReturn::auto($result);
    }
}